package JavaUtils.web;


import JavaUtils.CSUtils.Log.CLog;
import JavaUtils.web.req.WebReq_Register;
import JavaUtils.web.req.io.Req_directory;
import JavaUtils.web.req.io.Req_fileRead;
import JavaUtils.web.req.io.Req_fileUpload;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

public class CWebServer {
    static final String tag = "CWebServer";
    public static String charset = "utf-8";
    static int PORT = 8899;
    ServerSocket ss;
    Socket client;

    public static void S_WebListener(int PORT, Map<String, IWebCallback> eventMap) {
        new CWebServer(PORT, eventMap);
    }

    public CWebServer(int PORT, Map<String, IWebCallback> eventMap) {
        CWebServer.PORT = PORT;
        CWebClientThread.o_eventMap = eventMap;
        WebReq_Register.Register(eventMap);

        try {
            this.ss = new ServerSocket(CWebServer.PORT);
            CLog.i(tag,"服务器侦听端口 " + CWebServer.PORT + "...");
            boolean isGo = true;
            while (isGo) {
                this.client = this.ss.accept();
                CLog.i(tag,"新链接客户端..... " + this.client);
                CWebClientThread ct = new CWebClientThread(this.client);
                Thread t = new Thread(ct);
                t.start();
                CLog.i(tag,"一个客户端线程已经启动...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (this.ss != null) {
                    this.ss.close();
                    this.ss = null;
                }
                if (this.client != null) {
                    this.client.close();
                    this.client = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}